package shell.listener;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JList;
import javax.swing.JTextField;
/**@author Rafael Rocha*/
public class SelectVarListener implements ActionListener{
	private JList list;
	private JTextField varField;
	
	public SelectVarListener(JList list, JTextField varField){
		this.varField = varField;
		this.list = list;
	}

	@Override
	public void actionPerformed(ActionEvent arg0) {
		
		String text = varField.getText();
		int first = list.getSelectedIndex();
		int selected = -1;
		
		for(int i = first+1; i < list.getModel().getSize() ; i++){
			if(((String)list.getModel().getElementAt(i)).contains(text)){
				selected = i;
				break;
			}
		}
		if(selected == -1){
			for(int i = 0; i < first ; i++){
				if(((String)list.getModel().getElementAt(i)).contains(text)){
					selected = i;
					break;
				}
			}
		}
		if(selected != -1){
			list.ensureIndexIsVisible(selected);
			list.setSelectedIndex(selected);
		}
	}
}
